const express = require('express')
const router = express.Router();
const mongoose = require('../db/db.js');
const deviceShe = require('../db/deviceShe')
const groupShe = require('../db/groupShe')
const debug = require('debug')('a-sokio-yun:server');

router.get('/', function (req, res) {
  let userName = req.session.userName
  if (!userName) {
    return res.json({
      msg: "请刷新浏览器重新登录"
    })
  }

  let query = req.query//{ page, limit }

  let daiLi_userName = query.daiLi_userName

  if (daiLi_userName) {
    console.log("daiLi_userName" + daiLi_userName);
    userName = daiLi_userName
  }

  let deviceMod = mongoose.model('device_' + userName, deviceShe)


  let searchDic = {}
  if (query.type == "arr") {
    // console.log(query.deviceName);
    // console.log(typeof (query.deviceName));
    if (query.deviceName && query.deviceName != "") {
      // searchDic.deviceName = { $in: query.deviceName }
      searchDic.deviceName = { $in: deviceArr(query.deviceName) }
    }
  } else {
    if (query.deviceName && query.deviceName != "") {
      // searchDic.deviceName = query.deviceName
      searchDic.deviceName = { $regex: query.deviceName }
    }
  }


  if (query.taskStatus && query.taskStatus != "") {
    searchDic.taskStatus = query.taskStatus
  }

  // if (query.groupId && query.groupId != "") {
  //   searchDic.groupId = null//{ $exists: false }
  // }

  if (query.groupId) {
    if (query.groupId == "空的") {
      searchDic.groupId = null//{ $exists: false }
    } else {
      searchDic.groupId = query.groupId
    }
  }

  resPcData(deviceMod, res, searchDic, query)

});

//新增分组
router.post('/', function (req, res) {
  let userName = req.session.userName
  if (!userName) {
    return res.json({
      msg: "请刷新浏览器重新登录"
    })
  }


  let query = req.body//{ page, limit }
  // console.log(query);
  let searchDic = { groupId: null }//{ $exists: false }

  adddGroup(res, searchDic, query, userName)

});

async function adddGroup(res, searchDic, query, userName) {
  let deviceMod = mongoose.model('device_' + userName, deviceShe)
  let groupMod = mongoose.model('group_' + userName, groupShe)
  let checkData = JSON.parse(query.checkData)
  let groupName = query.groupName
  let groupDoc = await groupMod.findOneAndUpdate({ groupName: groupName }, { groupName: groupName }, { upsert: true, new: true })
  // console.log("新增或者刷新分组,组名:" + groupDoc.groupName)
  // console.log(checkData)
  for (let i = 0; i < checkData.length; i++) {
    await deviceMod.updateOne({ _id: checkData[i]._id }, { groupId: groupDoc._id })
  }
  resPcData(deviceMod, res, searchDic, query)
}



//从组内删除设备
router.get('/delDevice', async function (req, res) {
  let userName = req.session.userName
  if (!userName) {
    return res.json({
      msg: "请刷新浏览器重新登录"
    })
  }
  let query = req.query
  let deviceMod = mongoose.model('device_' + userName, deviceShe)
  await deviceMod.updateOne({ _id: query.deviceId }, { groupId: null }, { upsert: false })
  asyncResPcData(res, query, deviceMod)
});

async function asyncResPcData(res, query, deviceMod) {
  let groupId = query.groupId
  let findDic = { groupId: groupId }
  if (groupId == "空闲") {
    findDic = { taskStatus: "空闲" }
  } else if (groupId == "忙碌") {
    findDic = { taskStatus: "忙碌" }
  } else if (groupId == "全部") {
    findDic = {}
  }

  if (query.type == "arr") {
    // console.log(query.deviceName);
    // console.log(typeof (query.deviceName));
    if (query.deviceName && query.deviceName != "") {
      // findDic.deviceName = { $in: query.deviceName }
      findDic.deviceName = { $in: deviceArr(query.deviceName) }
    }
  } else {
    if (query.deviceName && query.deviceName != "") {
      // findDic.deviceName = query.deviceName
      findDic.deviceName = { $regex: query.deviceName }
    }
  }

  try {
    const devices = await deviceMod.find(findDic).sort({ 'deviceName': 1 })
    if (devices) {
      res.json({
        code: 0,
        msg: "",
        count: devices.length,
        data: devices
      });
    }
  } catch (error) {
    res.json({
      msg: error.message,
      code: 1,
      count: 0,
      data: []
    });
  }
}



//从设备列表删除设备
router.post('/delList',   async function (req, res) {//这里出现500报错
  let userName = req.session.userName
  if (!userName) {
    return res.json({
      msg: "请刷新浏览器重新登录"
    })
  }

  res.locals.username = userName;
  let query = req.body
  let devicesData = JSON.parse(query.devicesData)

  let daiLi_userName = query.daiLi_userName
  if (daiLi_userName) {
    userName = daiLi_userName
  }

  let deviceMod = mongoose.model('device_' + userName, deviceShe)
  //批量删除设备
  devicesData.forEach(async devicesDic => {
        await deviceMod.deleteOne({ _id: devicesDic._id })
  })

  resPcData(deviceMod, res, {}, query)

})

router.get('/groupDevice', function (req, res) {
  let userName = req.session.userName
  if (!userName) {
    return res.json({
      msg: "请刷新浏览器重新登录"
    })
  }

  let deviceMod = mongoose.model('device_' + userName, deviceShe)
  let query = req.query//{ page, limit }

  asyncResPcData(res, query, deviceMod)

});


async function resPcData(dbMod, res, serchDic, query) {
  try {
    const count = await dbMod.countDocuments(serchDic);
    const docs = await dbMod.find(serchDic).sort({ 'deviceName': 1 }).skip((query.page - 1) * query.limit).limit(parseInt(query.limit) || 20).exec();
    //.sort({ 'ciLength': 1 })
    // console.log("docs", docs);
    res.json({
      code: 0,
      msg: '',
      count: count,
      data: docs
    });
  } catch (error) {
    res.json({
      msg: "错误:" + error.message
    });
  }
}



function deviceArr(groupRule) {
  let device_arr = []
  groupRule.split(",").forEach(element => {
    if (element.indexOf("-") > -1) {
      let index_min_max = element.split("-")
      var qianZui = index_min_max[0].match(/^[^\d]*[0]*/)
      if (qianZui) {
        console.log(qianZui);
        qianZui = qianZui[0]
      } else {
        qianZui = ""
      }
      let index_min = parseInt(index_min_max[0].match(/\d+/)[0])

      let index_max = parseInt(index_min_max[1].match(/\d+/)[0])
      //看下去前缀和0后的最小数的位数
      let count_initMin = index_min.toString().length

      for (let i = index_min; i <= index_max; i++) {
        //每增加一位数,减少一个前缀0
        let len_add = i.toString().length - count_initMin
        let str0 = ""
        let newQianZui = qianZui
        for (let j = 0; j < len_add; j++) {
          newQianZui = newQianZui.replace('0', '')
        }
        device_arr.push(newQianZui + i)
      }
    } else {
      device_arr.push(element)
    }
  });
  // console.log(device_arr)
  return device_arr
}



// 标记设备类型
router.post('/markDeviceType', async function (req, res) {
  let userName = req.session.userName;
  if (!userName) {
    return res.json({
      code: 1,
      msg: "请刷新浏览器重新登录"
    });
  }

  let { devicesData, deviceType, daiLi_userName } = req.body;
  
  if (daiLi_userName) {
    userName = daiLi_userName;
  }

  try {
    let devices = JSON.parse(devicesData);
    let deviceMod = mongoose.model('device_' + userName, deviceShe);
    
    // 批量更新设备类型
    let deviceIds = devices.map(device => device._id);
    
    await deviceMod.updateMany(
      { _id: { $in: deviceIds } },
      { $set: { deviceType: deviceType } }
    );
    
    res.json({
      code: 0,
      msg: "标记成功",
      count: devices.length
    });
    
  } catch (error) {
    console.error('标记设备类型失败:', error);
    res.json({
      code: 1,
      msg: "标记失败: " + error.message
    });
  }
});

module.exports = router;